import React, { useMemo, useState, useRef, useCallback } from 'react';
import ReactDOM from 'react-dom';
import Draggable from 'react-draggable';
import './drag.css';

const Drag = () => {
  const [bounds, setBounds] = useState({
    initialLeftBoxWidth: 250, // 左边区块初始宽度
    leftBoxWidth: 250, // 左边区块初始宽度
    leftBoxMinWidth: 200, // 左边区块最小宽度
    leftBoxMaxWidth: window.screen.width / 3, // 左边区块最大宽度
    dragBoxBackground: 'transparent', // 拖拽盒子的背景色
  });

  // 拖动时设置拖动box背景色，同时更新左右box的宽度
  const onDrag = (ev, ui) => {
    const initialLeftBoxWidth = bounds.initialLeftBoxWidth;
    const newLeftBoxWidth = ui.x + initialLeftBoxWidth;
    setBounds({
      ...bounds,
      leftBoxWidth: newLeftBoxWidth,
      dragBoxBackground: '#1890ff',
    });
  };

  // 拖拽结束，重置drag-box的背景色
  const onDragStop = () => {
    setBounds({
      ...bounds,
      dragBoxBackground: 'transparent',
    });
  };

  return (
    <>
      <div className="data-dev-wrapper">
        <div
          className="data-dev-wrapper-left"
          style={{ width: bounds.leftBoxWidth }}
        >
          <div>
            <h3 style={{ paddingLeft: 20 }}>目录</h3>
            <ul style={{ paddingLeft: 20 }}>
              <li>目录1</li>
              <li>目录2</li>
              <li>目录3</li>
              <li>这是个非常长非常长非常长的目录</li>
            </ul>
          </div>
          <Draggable
            axis="x"
            defaultPosition={{ x: 0, y: 0 }}
            bounds={{
              left: bounds.leftBoxMinWidth - bounds.initialLeftBoxWidth,
              right: bounds.leftBoxMaxWidth - bounds.initialLeftBoxWidth,
            }}
            onDrag={onDrag}
            onStop={onDragStop}
          >
            <div
              className="drag-box"
              style={{
                left: bounds.initialLeftBoxWidth - 5,
                background: bounds.dragBoxBackground,
              }}
            ></div>
          </Draggable>
        </div>
        <div className="data-dev-wrapper-right"></div>
      </div>
    </>
  );
};

ReactDOM.render(<Drag />, document.getElementById('root'));
